<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>角色管理 - 粮食收购大数据平台</title>
    <!-- Element Plus CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <!-- Vue 3 -->
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <!-- Element Plus JS -->
    <script src="https://unpkg.com/element-plus/dist/index.full.js"></script>
    <!-- Element Plus Icons -->
    <script src="https://unpkg.com/@element-plus/icons-vue/dist/index.iife.js"></script>
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
            font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
        }
        .page-container {
            max-width: 1400px;
            margin: 0 auto;
        }
        .page-header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .page-title {
            font-size: 24px;
            font-weight: 600;
            color: #333;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .page-title i {
            color: #4CAF50;
        }
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        .stat-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
        }
        .stat-icon {
            font-size: 32px;
            margin-bottom: 10px;
        }
        .stat-icon.total { color: #409EFF; }
        .stat-icon.active { color: #67C23A; }
        .stat-icon.inactive { color: #F56C6C; }
        .stat-icon.admin { color: #E6A23C; }
        .stat-value {
            font-size: 28px;
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }
        .stat-label {
            font-size: 14px;
            color: #666;
        }
        .content-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .search-bar {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
            flex-wrap: wrap;
            align-items: center;
        }
        .search-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .search-item label {
            font-size: 14px;
            color: #666;
            white-space: nowrap;
        }
        .table-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .table-title {
            font-size: 16px;
            font-weight: 600;
            color: #333;
        }
        .role-tag {
            margin-right: 5px;
        }
        .permission-tags {
            max-width: 300px;
        }
        .permission-tag {
            margin: 2px;
            font-size: 12px;
        }
        .dialog-form {
            padding: 20px 0;
        }
        .form-section {
            margin-bottom: 20px;
        }
        .form-section-title {
            font-size: 14px;
            font-weight: 600;
            color: #333;
            margin-bottom: 10px;
            border-left: 3px solid #4CAF50;
            padding-left: 10px;
        }
        .permission-tree {
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            padding: 10px;
            max-height: 300px;
            overflow-y: auto;
        }
        @media (max-width: 768px) {
            .search-bar {
                flex-direction: column;
                align-items: stretch;
            }
            .search-item {
                flex-direction: column;
                align-items: stretch;
            }
            .table-header {
                flex-direction: column;
                gap: 10px;
                align-items: stretch;
            }
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="page-container">
            <!-- 页面头部 -->
            <div class="page-header">
                <h1 class="page-title">
                    <i class="fas fa-user-shield"></i>
                    角色管理
                </h1>
            </div>

            <!-- 统计卡片 -->
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-icon total">
                        <i class="fas fa-users-cog"></i>
                    </div>
                    <div class="stat-value">{{ totalRoles }}</div>
                    <div class="stat-label">总角色数</div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon active">
                        <i class="fas fa-check-circle"></i>
                    </div>
                    <div class="stat-value">{{ activeRoles }}</div>
                    <div class="stat-label">启用角色</div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon inactive">
                        <i class="fas fa-times-circle"></i>
                    </div>
                    <div class="stat-value">{{ inactiveRoles }}</div>
                    <div class="stat-label">禁用角色</div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon admin">
                        <i class="fas fa-crown"></i>
                    </div>
                    <div class="stat-value">{{ adminRoles }}</div>
                    <div class="stat-label">管理员角色</div>
                </div>
            </div>

            <!-- 主要内容 -->
            <div class="content-card">
                <!-- 搜索栏 -->
                <div class="search-bar">
                    <div class="search-item">
                        <label>关键词：</label>
                        <el-input
                            v-model="searchForm.keyword"
                            placeholder="请输入角色名称或描述"
                            style="width: 200px;"
                            clearable>
                        </el-input>
                    </div>
                    <div class="search-item">
                        <label>状态：</label>
                        <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 120px;" clearable>
                            <el-option label="启用" value="1"></el-option>
                            <el-option label="禁用" value="0"></el-option>
                        </el-select>
                    </div>
                    <div class="search-item">
                        <label>角色类型：</label>
                        <el-select v-model="searchForm.roleType" placeholder="请选择类型" style="width: 150px;" clearable>
                            <el-option label="系统管理员" value="admin"></el-option>
                            <el-option label="政府部门" value="government"></el-option>
                            <el-option label="集团公司" value="group"></el-option>
                            <el-option label="收购企业" value="factory"></el-option>
                            <el-option label="普通用户" value="user"></el-option>
                        </el-select>
                    </div>
                    <el-button type="primary" @click="searchRoles">
                        <i class="fas fa-search"></i> 搜索
                    </el-button>
                    <el-button @click="resetSearch">
                        <i class="fas fa-redo"></i> 重置
                    </el-button>
                </div>

                <!-- 表格头部 -->
                <div class="table-header">
                    <div class="table-title">角色列表</div>
                    <div>
                        <el-button type="primary" @click="showAddDialog">
                            <i class="fas fa-plus"></i> 新增角色
                        </el-button>
                        <el-button type="success" @click="exportData">
                            <i class="fas fa-download"></i> 导出数据
                        </el-button>
                    </div>
                </div>

                <!-- 数据表格 -->
                <el-table :data="filteredRoles" style="width: 100%" v-loading="loading">
                    <el-table-column prop="id" label="ID" width="80" sortable></el-table-column>
                    <el-table-column prop="roleName" label="角色名称" width="150">
                        <template #default="scope">
                            <el-tag :type="getRoleTagType(scope.row.roleType)" class="role-tag">
                                {{ scope.row.roleName }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="roleCode" label="角色代码" width="120"></el-table-column>
                    <el-table-column prop="roleType" label="角色类型" width="120">
                        <template #default="scope">
                            <span>{{ getRoleTypeText(scope.row.roleType) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="description" label="角色描述" min-width="200"></el-table-column>
                    <el-table-column prop="permissions" label="权限数量" width="100">
                        <template #default="scope">
                            <el-tag type="info">{{ scope.row.permissions.length }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="userCount" label="用户数量" width="100">
                        <template #default="scope">
                            <el-tag type="warning">{{ scope.row.userCount }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="80">
                        <template #default="scope">
                            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                                {{ scope.row.status === 1 ? '启用' : '禁用' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" width="180" sortable></el-table-column>
                    <el-table-column label="操作" width="200" fixed="right">
                        <template #default="scope">
                            <el-button size="small" @click="viewRole(scope.row)">
                                <i class="fas fa-eye"></i> 查看
                            </el-button>
                            <el-button size="small" type="primary" @click="editRole(scope.row)">
                                <i class="fas fa-edit"></i> 编辑
                            </el-button>
                            <el-button size="small" type="danger" @click="deleteRole(scope.row)" :disabled="scope.row.userCount > 0">
                                <i class="fas fa-trash"></i> 删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div style="margin-top: 20px; text-align: center;">
                    <el-pagination
                        v-model:current-page="currentPage"
                        v-model:page-size="pageSize"
                        :page-sizes="[10, 20, 50, 100]"
                        :total="totalCount"
                        layout="total, sizes, prev, pager, next, jumper">
                    </el-pagination>
                </div>
            </div>
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog
            :title="dialogTitle"
            v-model="dialogVisible"
            width="600px"
            :before-close="handleClose">
            <div class="dialog-form">
                <el-form :model="roleForm" :rules="rules" ref="roleFormRef" label-width="100px">
                    <div class="form-section">
                        <div class="form-section-title">基本信息</div>
                        <el-form-item label="角色名称" prop="roleName">
                            <el-input v-model="roleForm.roleName" placeholder="请输入角色名称"></el-input>
                        </el-form-item>
                        <el-form-item label="角色代码" prop="roleCode">
                            <el-input v-model="roleForm.roleCode" placeholder="请输入角色代码"></el-input>
                        </el-form-item>
                        <el-form-item label="角色类型" prop="roleType">
                            <el-select v-model="roleForm.roleType" placeholder="请选择角色类型" style="width: 100%;">
                                <el-option label="系统管理员" value="admin"></el-option>
                                <el-option label="政府部门" value="government"></el-option>
                                <el-option label="集团公司" value="group"></el-option>
                                <el-option label="收购企业" value="factory"></el-option>
                                <el-option label="普通用户" value="user"></el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="角色描述" prop="description">
                            <el-input type="textarea" v-model="roleForm.description" placeholder="请输入角色描述" :rows="3"></el-input>
                        </el-form-item>
                        <el-form-item label="状态" prop="status">
                            <el-radio-group v-model="roleForm.status">
                                <el-radio :label="1">启用</el-radio>
                                <el-radio :label="0">禁用</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </div>
                    
                    <div class="form-section">
                        <div class="form-section-title">权限配置</div>
                        <el-form-item label="菜单权限">
                            <div class="permission-tree">
                                <el-tree
                                    ref="permissionTreeRef"
                                    :data="menuList"
                                    :props="{ children: 'children', label: 'menu_name' }"
                                    show-checkbox
                                    node-key="id"
                                    :default-checked-keys="roleForm.permissions">
                                </el-tree>
                            </div>
                        </el-form-item>
                    </div>
                </el-form>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveRole">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>

    <script>
        const { createApp, ref, computed, onMounted } = Vue;
        const { ElMessage, ElMessageBox } = ElementPlus;

        createApp({
            setup() {
                // 响应式数据
                const loading = ref(false);
                const currentPage = ref(1);
                const pageSize = ref(20);
                const totalCount = ref(0);
                const dialogVisible = ref(false);
                const isEdit = ref(false);
                
                // 搜索表单
                const searchForm = ref({
                    keyword: '',
                    status: '',
                    roleType: ''
                });
                
                // 角色表单
                const roleForm = ref({
                    id: null,
                    roleName: '',
                    roleCode: '',
                    roleType: '',
                    description: '',
                    status: 1,
                    permissions: []
                });
                
                // 表单验证规则
                const rules = {
                    roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
                    roleCode: [{ required: true, message: '请输入角色代码', trigger: 'blur' }],
                    roleType: [{ required: true, message: '请选择角色类型', trigger: 'change' }],
                    description: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
                };
                
                // 模拟角色数据
                const roleList = ref([
                    {
                        id: 1,
                        roleName: '超级管理员',
                        roleCode: 'super_admin',
                        roleType: 'admin',
                        description: '系统超级管理员，拥有所有权限',
                        permissions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
                        userCount: 2,
                        status: 1,
                        createTime: '2024-01-15 10:30:00'
                    },
                    {
                        id: 2,
                        roleName: '系统管理员',
                        roleCode: 'system_admin',
                        roleType: 'admin',
                        description: '系统管理员，负责系统配置和用户管理',
                        permissions: [1, 2, 3, 4],
                        userCount: 5,
                        status: 1,
                        createTime: '2024-01-20 14:20:00'
                    },
                    {
                        id: 3,
                        roleName: '政府监管员',
                        roleCode: 'gov_supervisor',
                        roleType: 'government',
                        description: '政府部门监管人员，负责数据监管和统计',
                        permissions: [5, 6, 7, 8, 9, 15, 16, 17, 18],
                        userCount: 8,
                        status: 1,
                        createTime: '2024-02-01 09:15:00'
                    },
                    {
                        id: 4,
                        roleName: '集团管理员',
                        roleCode: 'group_admin',
                        roleType: 'group',
                        description: '集团公司管理员，管理下属企业和业务数据',
                        permissions: [10, 11, 12, 13, 14, 15, 16, 17],
                        userCount: 12,
                        status: 1,
                        createTime: '2024-02-10 16:45:00'
                    },
                    {
                        id: 5,
                        roleName: '加工厂管理员',
                        roleCode: 'factory_admin',
                        roleType: 'factory',
                        description: '加工厂管理员，管理本厂收购和生产数据',
                        permissions: [12, 13, 14, 15, 16],
                        userCount: 25,
                        status: 1,
                        createTime: '2024-02-15 11:30:00'
                    },
                    {
                        id: 6,
                        roleName: '数据录入员',
                        roleCode: 'data_entry',
                        roleType: 'user',
                        description: '数据录入人员，负责基础数据录入',
                        permissions: [13, 14],
                        userCount: 45,
                        status: 1,
                        createTime: '2024-03-01 08:20:00'
                    },
                    {
                        id: 7,
                        roleName: '财务人员',
                        roleCode: 'finance',
                        roleType: 'user',
                        description: '财务人员，负责财务数据管理',
                        permissions: [15, 16, 17],
                        userCount: 8,
                        status: 1,
                        createTime: '2024-03-05 13:40:00'
                    },
                    {
                        id: 8,
                        roleName: '临时角色',
                        roleCode: 'temp_role',
                        roleType: 'user',
                        description: '临时测试角色',
                        permissions: [13],
                        userCount: 0,
                        status: 0,
                        createTime: '2024-03-10 15:20:00'
                    }
                ]);
                
                // 菜单权限数据（基于Menu表结构）
                const menuList = ref([
                    {
                        id: 1,
                        menu_name: '系统管理',
                        children: [
                            { id: 2, menu_name: '用户管理', description: '管理系统用户账户' },
                            { id: 3, menu_name: '角色管理', description: '管理用户角色权限' },
                            { id: 4, menu_name: '菜单管理', description: '管理系统菜单结构' }
                        ]
                    },
                    {
                        id: 5,
                        menu_name: '组织管理',
                        children: [
                            { id: 6, menu_name: '省/兵团管理', description: '管理省份和兵团信息' },
                            { id: 7, menu_name: '市级管理', description: '管理市级行政区域' },
                            { id: 8, menu_name: '区县管理', description: '管理区县级行政区域' },
                            { id: 9, menu_name: '乡镇管理', description: '管理乡镇级行政区域' }
                        ]
                    },
                    {
                        id: 10,
                        menu_name: '业务管理',
                        children: [
                            { id: 11, menu_name: '集团管理', description: '管理集团信息' },
                            { id: 12, menu_name: '加工厂管理', description: '管理加工厂信息' },
                            { id: 13, menu_name: '农户管理', description: '管理农户基础信息' },
                            { id: 14, menu_name: '地块管理', description: '管理农田地块信息' }
                        ]
                    },
                    {
                        id: 15,
                        menu_name: '数据统计',
                        children: [
                            { id: 16, menu_name: '收购统计', description: '粮食收购数据统计' },
                            { id: 17, menu_name: '销售统计', description: '粮食销售数据统计' },
                            { id: 18, menu_name: '库存统计', description: '库存数据统计分析' }
                        ]
                    }
                ]);
                
                // 计算属性
                const totalRoles = computed(() => roleList.value.length);
                const activeRoles = computed(() => roleList.value.filter(role => role.status === 1).length);
                const inactiveRoles = computed(() => roleList.value.filter(role => role.status === 0).length);
                const adminRoles = computed(() => roleList.value.filter(role => role.roleType === 'admin').length);
                
                const dialogTitle = computed(() => isEdit.value ? '编辑角色' : '新增角色');
                
                const filteredRoles = computed(() => {
                    let filtered = roleList.value;
                    
                    if (searchForm.value.keyword) {
                        const keyword = searchForm.value.keyword.toLowerCase();
                        filtered = filtered.filter(role => 
                            role.roleName.toLowerCase().includes(keyword) ||
                            role.description.toLowerCase().includes(keyword)
                        );
                    }
                    
                    if (searchForm.value.status !== '') {
                        filtered = filtered.filter(role => role.status === parseInt(searchForm.value.status));
                    }
                    
                    if (searchForm.value.roleType) {
                        filtered = filtered.filter(role => role.roleType === searchForm.value.roleType);
                    }
                    
                    totalCount.value = filtered.length;
                    return filtered;
                });
                
                // 方法
                const getRoleTagType = (roleType) => {
                    const typeMap = {
                        'admin': 'danger',
                        'government': 'warning',
                        'group': 'primary',
                        'factory': 'success',
                        'user': 'info'
                    };
                    return typeMap[roleType] || 'info';
                };
                
                const getRoleTypeText = (roleType) => {
                    const typeMap = {
                        'admin': '系统管理员',
                        'government': '政府部门',
                        'group': '集团公司',
                        'factory': '收购企业',
                        'user': '普通用户'
                    };
                    return typeMap[roleType] || '未知';
                };
                
                const searchRoles = () => {
                    loading.value = true;
                    // 模拟搜索延迟
                    setTimeout(() => {
                        loading.value = false;
                        ElMessage.success('搜索完成');
                    }, 500);
                };
                
                const resetSearch = () => {
                    searchForm.value = {
                        keyword: '',
                        status: '',
                        roleType: ''
                    };
                    ElMessage.info('搜索条件已重置');
                };
                
                const showAddDialog = () => {
                    isEdit.value = false;
                    roleForm.value = {
                        id: null,
                        roleName: '',
                        roleCode: '',
                        roleType: '',
                        description: '',
                        status: 1,
                        permissions: []
                    };
                    dialogVisible.value = true;
                };
                
                const viewRole = (role) => {
                    ElMessage.info(`查看角色：${role.roleName}`);
                };
                
                const editRole = (role) => {
                    isEdit.value = true;
                    roleForm.value = { ...role };
                    dialogVisible.value = true;
                };
                
                const deleteRole = (role) => {
                    if (role.userCount > 0) {
                        ElMessage.warning('该角色下还有用户，无法删除');
                        return;
                    }
                    
                    ElMessageBox.confirm(
                        `确定要删除角色 "${role.roleName}" 吗？`,
                        '确认删除',
                        {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning',
                        }
                    ).then(() => {
                        const index = roleList.value.findIndex(r => r.id === role.id);
                        if (index > -1) {
                            roleList.value.splice(index, 1);
                            ElMessage.success('删除成功');
                        }
                    }).catch(() => {
                        ElMessage.info('已取消删除');
                    });
                };
                
                const saveRole = () => {
                    // 获取选中的权限
                    const checkedKeys = this.$refs.permissionTreeRef.getCheckedKeys();
                    roleForm.value.permissions = checkedKeys;
                    
                    if (isEdit.value) {
                        // 编辑角色
                        const index = roleList.value.findIndex(r => r.id === roleForm.value.id);
                        if (index > -1) {
                            roleList.value[index] = { ...roleForm.value };
                            ElMessage.success('角色更新成功');
                        }
                    } else {
                        // 新增角色
                        const newRole = {
                            ...roleForm.value,
                            id: Date.now(), // 简单的ID生成
                            userCount: 0,
                            createTime: new Date().toLocaleString('zh-CN')
                        };
                        roleList.value.unshift(newRole);
                        ElMessage.success('角色创建成功');
                    }
                    
                    dialogVisible.value = false;
                };
                
                const handleClose = () => {
                    dialogVisible.value = false;
                };
                
                const exportData = () => {
                    ElMessage.success('数据导出功能开发中...');
                };
                
                // 生命周期
                onMounted(() => {
                    // 初始化数据
                });
                
                return {
                    loading,
                    currentPage,
                    pageSize,
                    totalCount,
                    dialogVisible,
                    isEdit,
                    searchForm,
                    roleForm,
                    rules,
                    roleList,
                    menuList,
                    totalRoles,
                    activeRoles,
                    inactiveRoles,
                    adminRoles,
                    dialogTitle,
                    filteredRoles,
                    getRoleTagType,
                    getRoleTypeText,
                    searchRoles,
                    resetSearch,
                    showAddDialog,
                    viewRole,
                    editRole,
                    deleteRole,
                    saveRole,
                    handleClose,
                    exportData
                };
            }
        }).use(ElementPlus).mount('#app');
    </script>
</body>
</html>